package com.rem.se.reflect;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 使用反射的性能测试
 *
 * @author Rem
 * @date 2021-03-15
 */

public class Demo08 {

    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        test1();
        test2();
        test3();
    }

    private static void test1() {
        User user = new User();
        long start = System.currentTimeMillis();
        for (Long i = 0L; i < 20000000L; i++) {
            user.getName();
        }
        long end = System.currentTimeMillis();

        System.err.println("普通get需要时长:" + (end - start));
    }

    private static void test2() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        User user = new User();
        Class aClass = user.getClass();
        Method getName = aClass.getDeclaredMethod("getName", null);
        getName.invoke(user,null);
        long start = System.currentTimeMillis();
        for (int i = 0; i < 20000000L; i++) {
            getName.getName();
        }
        long end = System.currentTimeMillis();

        System.err.println("反射方式get需要时长:" + (end - start));
    }

    private static void test3() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        User user = new User();
        Class<? extends User> aClass = user.getClass();
        Method getName = aClass.getDeclaredMethod("getName", null);
        getName.invoke(user,null);
        getName.setAccessible(true);

        long start = System.currentTimeMillis();
        for (int i = 0; i < 20000000L; i++) {
            getName.getName();
        }
        long end = System.currentTimeMillis();

        System.err.println("反射方式调用，关闭安全监测调用执行get需要时长:" + (end - start));
    }
}
